package com.ahstu.learning.friend;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import android.widget.Toast;

import com.ahstu.learning.R;
import com.ahstu.learning.base.BaseFragment;
import com.ahstu.learning.bean.User;
import com.ahstu.learning.event.ChatEvent;
import com.ahstu.learning.model.UserModel;
import com.ahstu.learning.notepad.ListActivity;
import com.ahstu.learning.phoneContacts.tongxunlu;
import com.ahstu.learning.ui.SearchUserActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;

public class FriendFragement extends BaseFragment implements OnChildClickListener, View.OnClickListener {
    private Context context;
    public ImageView avatar;
    int[] images;
    String[] groupDate;
    List<String> child;
    ExpandableListView listView;
    ExpandAdapter adapter;
    List<List<String>> childrenData;
    ImageView iv_addFriend;
    ImageView iv_contacts_phone;
    ImageView iv_notepad;
    SwipeRefreshLayout friendRefresh;
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        listView = (ExpandableListView) view.findViewById(R.id.expandAdapterList);
        friendRefresh = (SwipeRefreshLayout) view.findViewById(R.id.friend_refresh);
        iv_addFriend = (ImageView) view.findViewById(R.id.find_friend);
        iv_contacts_phone = (ImageView) view.findViewById(R.id.contacts_phone);
        iv_notepad = (ImageView) view.findViewById(R.id.notepad);
        iv_addFriend.setOnClickListener(this);
        iv_contacts_phone.setOnClickListener(this);
        iv_notepad.setOnClickListener(this);
        query();
        friendRefresh.setEnabled(true);
        friendRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        query();
                        friendRefresh.setRefreshing(false);
                    }
                }, 1000);
            }
        });

    }


    private void query() {
        /**
         * ----------定义数组-------------------------------------------------------
         * ------------
         */
        images = new int[]{R.drawable.head};
        groupDate = new String[]{"良师益友"};
        childrenData = new ArrayList<List<String>>();
        child = new ArrayList<String>();
        //获取好友
        User user = UserModel.getInstance().getCurrentUser();
        final BmobQuery<FriendTable> query = new BmobQuery<FriendTable>();
        query.addWhereEqualTo("myName", user.getUsername());
        query.setLimit(1000);
        query.findObjects(getActivity(), new FindListener<FriendTable>() {

                    @Override
                    public void onSuccess(List<FriendTable> list) {
                        for (FriendTable friendTables : list) {
                            //从FriendTable中获取好友信息，从usr表中加载好友
                            final BmobQuery<User> query2 = new BmobQuery<User>();
                            query2.addWhereEqualTo("username", friendTables.getFriendName());
                            query2.setLimit(1);
                            query2.findObjects(getActivity(), new FindListener<User>() {
                                @Override
                                public void onSuccess(List<User> list) {
                                    for (User user1 : list) {
                                        child.add(user1.getUsername());
                                        childrenData.add(child);
                                        adapter = new ExpandAdapter(getActivity(), images, groupDate, childrenData);
                                        listView.setAdapter(adapter);
                                    }
                                }

                                @Override
                                public void onError(int i, String s) {
                                    Toast.makeText(getActivity(), "加载好友失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(int i, String s) {
                        Toast.makeText(getActivity(), "加载好友失败", Toast.LENGTH_SHORT).show();
                    }
                }

        );

        listView.setOnChildClickListener(this);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        return inflater.inflate(R.layout.base_friend, container, false);
    }

    //点击好友列表，
    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
                                int childPosition, long id) {
        BmobQuery<User> query = new BmobQuery<User>();
        query.addWhereEqualTo("username", adapter.getChild(groupPosition, childPosition));
        query.setLimit(1);
        query.findObjects(getActivity(), new FindListener<User>() {
            @Override
            public void onSuccess(List<User> list) {
                for (User user : list) {
                    BmobIMUserInfo info = new BmobIMUserInfo(user.getObjectId(), user.getUsername(), null);
                    EventBus.getDefault().post(new ChatEvent(info));

                }
            }

            @Override
            public void onError(int i, String s) {
                Toast.makeText(getActivity(), "好友不存在，请刷新好友列表", Toast.LENGTH_SHORT).show();
            }
        });

        return false;
    }

    //好友列表上面的imageView的响应
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.find_friend:
                startActivity(new Intent(getActivity(), SearchUserActivity.class));
                break;
            case R.id.contacts_phone:
                startActivity(new Intent(getActivity(), tongxunlu.class));
                break;
            case R.id.notepad:
                startActivity(new Intent(getActivity(), ListActivity.class));
                break;
        }
    }
}
